package com.hd.service.personaloffice.impl;

import com.hd.dao.BaseDao;
import com.hd.entity.*;
import com.hd.entity.enums.*;
import com.hd.entity.personaloffice.WorkCommentOpinion;
import com.hd.entity.personaloffice.WorkPlan;
import com.hd.entity.sys.User;
import com.hd.service.*;
import com.hd.service.job.QuartzScheduleJobService;
import com.hd.service.personaloffice.WorkCommentOpinionService;
import com.hd.service.personaloffice.WorkPlanService;
import com.hd.service.sys.UserService;
import com.hd.util.StringUtils;
import com.hd.util.result.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: hzhh123
 * @Date: 2018/12/24 23:03
 * 工作计划
 */
@Service("workPlanService")
public class WorkPlanServiceImpl implements WorkPlanService {
    @Autowired
    private BaseDao<WorkPlan,String>workPlanDao;
    @Autowired
    private WorkCommentOpinionService workCommentOpinionService;
    @Autowired
    private AttachService attachService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private UserService userService;
    @Autowired
    private QuartzScheduleJobService quartzScheduleJobService;
    @Autowired
    private TodoService todoService;
    @Autowired
    private WorkCcService workCcService;
    @Override
    public Serializable save(WorkPlan workPlan) {
        Date now=new Date();
        workPlan.setId(UUID.randomUUID().toString());
        workPlan.setOperateTime(now);
        workPlan.setSaveDate(now);
        String id=(String)workPlanDao.save(workPlan);
        saveWorkCommentOpinion(workPlan);
        return id;
    }

    /**
     * 保存待评论和抄送信息
     * @param workPlan
     */
    private void saveWorkCommentOpinion(WorkPlan workPlan){
        String msgIds="";
        String commentOpinionIds="";
        /**
         * 主送
         */
        if(StringUtils.isNotNull(workPlan.getCommentators())){
            String str[] = workPlan.getCommentators().split(",");
            for (String s : str) {
                saveObj1(workPlan,s);
            }
        }

        /**
         * 抄送
         */
        if(StringUtils.isNotNull(workPlan.getUseridCcs())){
            String str[] = workPlan.getUseridCcs().split(",");
            for (String s : str) {
               saveObj2(workPlan,s);
            }
        }
    }

    /**
     * 保存计划评论|消息|待办
     * @param workPlan
     * @param s
     */
    private void saveObj1(WorkPlan workPlan,String s){
        Msg msg=new Msg();
        msg.setType(MsgEnum.WORK_PLAN.getName());
        msg.setReceiver(s);
        msg.setContent(workPlan.getName()+"【待审批】");
        msg.setStatus(MsgStatusEnum.ON.getStatus());
        msg.setObjId(workPlan.getId());
        msgService.save(msg);
        /***********************保存待办******************/
        Todo todo=new Todo();
        todo.setCreateTime(new Date());
        todo.setObjId(workPlan.getId());
        todo.setStatus(TodoStatusEnum.TODO.getStatus());
        todo.setTitle(workPlan.getName());
        todo.setType(TodoTypeEnum.WORK_PLAN.getType());
        todo.setTypeName(TodoTypeEnum.WORK_PLAN.getMsg());
        todo.setUserId(s);
        todo.setOperatorURL(TodoTypeEnum.WORK_PLAN.getUrl()+workPlan.getId());
        todoService.save(todo);
        /***************************************************/
        WorkCommentOpinion opinion = new WorkCommentOpinion();
        opinion.setCommentator(s);
        opinion.setObjId(workPlan.getId());
        opinion.setType(WorkCommentOpinion.WORK_PLAN);
        workCommentOpinionService.save(opinion);
    }

    public void saveObj2(WorkPlan workPlan,String s){
        Msg msg=new Msg();
        msg.setType(MsgEnum.WORK_PLAN.getName());
        msg.setReceiver(s);
        msg.setObjId(workPlan.getId());
        msg.setContent(workPlan.getName()+"【抄送】");
        msg.setStatus(MsgStatusEnum.ON.getStatus());
        msgService.save(msg);
        //保存抄送
        WorkCc workCc=new WorkCc();
        workCc.setObjId(workPlan.getId());
        workCc.setTitle(workPlan.getName());
        workCc.setType(WorkCcTypeEnum.WORK_PLAN.getType());
        workCc.setTypeName(WorkCcTypeEnum.WORK_PLAN.getMsg());
        workCc.setUserId(s);
        workCc.setOperatorURL(WorkCcTypeEnum.WORK_PLAN.getPrefixUrl()+workPlan.getId());
        workCcService.save(workCc);

    }

    private void deleteObj1(String id,String userid){
        if(userid!=null) {
            //1)删除评论
            workCommentOpinionService.deleteByParams(id, userid, WorkCommentOpinion.WORK_PLAN);
            //2)删除消息
            msgService.deleteByParams(id, MsgEnum.WORK_PLAN.getName(), userid);
            //3)删除待办
            todoService.deleteByParams(id, TodoTypeEnum.WORK_PLAN.getType(), userid);
        }else {
            //1)删除评论
            workCommentOpinionService.deleteByParams(id, WorkCommentOpinion.WORK_PLAN);
            //2)删除消息
            msgService.deleteByParams(id, MsgEnum.WORK_PLAN.getName());
            //3)删除待办
            todoService.deleteByParams(id, TodoTypeEnum.WORK_PLAN.getType());
        }
    }
    private void deleteObj2(String id,String userid){
        if (userid!=null) {
            //1)删除消息
            msgService.deleteByParams(id, MsgEnum.WORK_PLAN.getName(), userid);
            //2)删除抄送
            workCcService.deleteByParams(id,WorkCcTypeEnum.WORK_PLAN.getType(),userid);
        }else {
            msgService.deleteByParams(id, MsgEnum.WORK_PLAN.getName());
            workCcService.deleteByParams(id,WorkCcTypeEnum.WORK_PLAN.getType());
        }
    }

    @Override
    public void update(WorkPlan workPlan) {
        WorkPlan vo=workPlanDao.get(WorkPlan.class,workPlan.getId());
        workPlan.setSaveDate(vo.getSaveDate());
        workPlan.setOperateTime(new Date());
        workPlan.setStatus(vo.getStatus());
        workPlan.setLastUpdateTime(new Date());
        String oldCommentators=vo.getCommentators();
        String oldUseridCcs=vo.getUseridCcs();
        workPlanDao.update(workPlan);
        saveNewCommentators(workPlan,oldCommentators);
        saveNewUseridCcs(workPlan,oldUseridCcs);

    }

    /**
     * 保存新增-删除审批人
     * @param workPlan
     * @param oldCommentators
     */
    private void saveNewCommentators(WorkPlan workPlan,String oldCommentators){
        String newCommentators=workPlan.getCommentators();
        if(StringUtils.isNotNull(newCommentators)){
            String s1[]=newCommentators.split(",");
            Set<String>set1=new HashSet<>();
            Set<String>set2=new HashSet<>();
            Set<String>set3=new HashSet<>();
            Set<String>result=new HashSet<>();
            for(String s:s1){
                set1.add(s);
                set2.add(s);
            }
            if (StringUtils.isNotNull(oldCommentators)) {
                //不为空，相同的不处理，不同需要增加或删除
                String s2[]=oldCommentators.split(",");
                for(String s:s2){
                    set3.add(s);
                }
                //set1与set3交集
                set1.retainAll(set3);
                result.clear();
                result.addAll(set2);
                result.removeAll(set1);
                //此时得到的是新增的部分
                if(result.size()>0){
                    for (String s:result){
                        saveObj1(workPlan,s);
                    }
                }
                result.clear();
                result.addAll(set3);
                result.removeAll(set1);
                if(result.size()>0){
                    //删除
                    for (String s:result){
                        deleteObj1(workPlan.getId(),s);
                    }
                }

            }else{
                //审批人为空，则直接插入
                for(String s:s1){
                    saveObj1(workPlan,s);
                }
            }
        }else{
            deleteObj1(workPlan.getId(),null);
        }
    } /**
     * 保存新增-删除抄送人
     * @param workPlan
     * @param oldUseridCcs
     */
    private void saveNewUseridCcs(WorkPlan workPlan,String oldUseridCcs){
        String newUseridCcs=workPlan.getUseridCcs();
        if(StringUtils.isNotNull(newUseridCcs)){
            String s1[]=newUseridCcs.split(",");
            Set<String>set1=new HashSet<>();
            Set<String>set2=new HashSet<>();
            Set<String>set3=new HashSet<>();
            Set<String>result=new HashSet<>();
            for(String s:s1){
                set1.add(s);
                set2.add(s);
            }
            if (StringUtils.isNotNull(oldUseridCcs)) {
                //不为空，相同的不处理，不同需要增加或删除
                String s2[]=oldUseridCcs.split(",");
                for(String s:s2){
                    set3.add(s);
                }
                //set1与set3交集
                set1.retainAll(set3);
                result.clear();
                result.addAll(set2);
                result.removeAll(set1);
                //此时得到的是新增的部分
                if(result.size()>0){
                    for (String s:result){
                        saveObj2(workPlan,s);
                    }
                }
                result.clear();
                result.addAll(set3);
                result.removeAll(set1);
                if(result.size()>0){
                    //删除
                    for (String s:result){
                        deleteObj2(workPlan.getId(),s);
                    }
                }

            }else{
                //审批人为空，则直接插入
                for(String s:s1){
                    saveObj2(workPlan,s);
                }
            }
        }else{
            deleteObj2(workPlan.getId(),null);
        }
    }


    @Override
    public WorkPlan get(String id) {
        WorkPlan workPlan=workPlanDao.get(WorkPlan.class,id);
        convert(workPlan);
        return workPlan;
    }

    /**
     * 封装其他参数
     * @param workPlan
     */
    private void convert(WorkPlan workPlan){
        if(StringUtils.isNotNull(workPlan.getUserid())){
            //查询用户
            User user=userService.get(workPlan.getUserid());
            if(user!=null){
                workPlan.setUserName(user.getName());
            }
        }
        //附件
        if(StringUtils.isNotNull(workPlan.getAttachIds())){
            List<Attach>attachList=attachService.findInIds(workPlan.getAttachIds());
            workPlan.setAttachList(attachList);
        }
        //评论
        if(StringUtils.isNotNull(workPlan.getCommentators())){
            List<WorkCommentOpinion>opinions=workCommentOpinionService.findByParams(workPlan.getId(),WorkCommentOpinion.WORK_PLAN);
            workPlan.setWorkCommentOpinionList(opinions);
            String commentatorNames="";
            if(opinions.size()>0) {
                for (WorkCommentOpinion opinion : opinions) {
                    commentatorNames += opinion.getCommentatorName() + ",";
                }
                commentatorNames = commentatorNames.substring(0, commentatorNames.lastIndexOf(","));
                workPlan.setCommentatorNames(commentatorNames);
            }
        }
        //抄送人
        if(StringUtils.isNotNull(workPlan.getUseridCcs())){
            List<User> users=userService.getUserByIds(workPlan.getUseridCcs());
            if(users.size()>0){
                String userNameCcs="";
                for(User user:users){
                    userNameCcs+=user.getName()+",";
                }
                userNameCcs=userNameCcs.substring(0,userNameCcs.lastIndexOf(","));
                workPlan.setUserNameCcs(userNameCcs);
            }
        }
    }
    @Override
    public void delete(String id) {
        //1)删除计划
        workPlanDao.delete(WorkPlan.class, id);
        //2)删除评论
        workCommentOpinionService.deleteByParams(id,WorkCommentOpinion.WORK_PLAN);
        //3)删除消息
        msgService.deleteByParams(id,MsgEnum.WORK_PLAN.getName());
        //4)删除待办
        todoService.deleteByParams(id,TodoTypeEnum.WORK_PLAN.getType());
        //5)删除抄送
        workCcService.deleteByParams(id,WorkCcTypeEnum.WORK_PLAN.getType());
    }

    @Override
    public void selectDataGrid(PageInfo info, WorkPlan workPlan) {
        Integer page=info.getNowpage();
        Integer pageSize=info.getPagesize();
        Map<String,Object> condition=info.getCondition();
        List<Object>params=new ArrayList<>();
        String hql="from WorkPlan where 1=1";
        if(StringUtils.isNotNull(workPlan.getUserid())){
            hql+=" and userid>=?";
            params.add(workPlan.getUserid());
        }
        if(StringUtils.isNotNull(workPlan.getSaveDateStart())){
            hql+=" and saveDate>=?";
            params.add(workPlan.getSaveDateStart());
        }

        if(StringUtils.isNotNull(workPlan.getSaveDateEnd())){
            hql+=" and saveDate<=?";
            params.add(workPlan.getSaveDateEnd());
        }
        if(StringUtils.isNotNull(workPlan.getName())){
            hql+=" and name like ?";
            params.add("%"+workPlan.getName()+"%");
        }

        if(StringUtils.isNotNull(workPlan.getPlanBelongTo())){
            hql+=" and planBelongTo like ?";
            params.add("%"+workPlan.getPlanBelongTo()+"%");
        }
        if(StringUtils.isNotNull(workPlan.getType())){
            hql+=" and type=?";
            params.add(workPlan.getType());
        }
        if(StringUtils.isNotNull(workPlan.getStatus())){
            hql+=" and status=? ";
            params.add(workPlan.getStatus());
        }else{
            hql+=" and status=? ";
            params.add(1);
        }

        hql+=" order by saveDate desc";
        String countSql="select count(*) "+hql;
        List<WorkPlan>workPlans=workPlanDao.findPage(hql,page,pageSize,params);
        if(workPlans.size()>0){
            for (WorkPlan workPlan1:workPlans){
                convert(workPlan1);
            }
        }
        info.setRows(workPlans);
        int total=Integer.parseInt(workPlanDao.getCountByList(countSql,params)+"");
        info.setTotal(total);

    }

    @Override
    public List<WorkPlan> getBySaveDate(Date saveDate,String userid) {
        String hql="from WorkPlan where saveDate=?  and userid=? and status=1";
        List<WorkPlan>workPlans=new ArrayList<>();
        workPlans=workPlanDao.find(hql,saveDate,userid);
        if(workPlans.size()>0){
            for(WorkPlan workPlan:workPlans){
                convert(workPlan);
            }
        }
        return workPlans;
    }

    @Override
    public List<WorkPlan> getByMonth(String date, String userid) throws Exception {
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String date1=date+"-01";
        String date2=date+"-31";
        Date d1=df.parse(date1);
        Date d2=df.parse(date2);
        String hql="from WorkPlan where saveDate>=? and saveDate<=? and userid=? and status=1";
        List<WorkPlan>workPlans=new ArrayList<>();
        workPlans=workPlanDao.find(hql,d1,d2,userid);
        if(workPlans.size()>0){
            for(WorkPlan workPlan:workPlans){
                convert(workPlan);
            }
        }
        return workPlans;
    }

    /**
     * 修改工作计划状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        String hql="update WorkPlan set status=?,lastUpdateTime=? where id=?";
        workPlanDao.execute(hql,status,new Date(),id);
        if(status==-1){
            //作废
            todoService.update(id,TodoStatusEnum.CANCEL.getStatus(),TodoTypeEnum.WORK_PLAN.getType());
            msgService.update(id,MsgStatusEnum.CANCEL.getStatus(),MsgEnum.WORK_PLAN.getName());
        }


    }
}
